package com.crm.api.controller;

import com.crm.api.common.Result;
import com.crm.api.entity.Customer;
import com.crm.api.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 客户控制器
 */
@Slf4j
@RestController
@RequestMapping("/customers")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    /**
     * 获取客户列表
     */
    @GetMapping
    public Result<Map<String, Object>> getCustomers(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String companyName,
            @RequestParam(required = false) String contactPerson,
            @RequestParam(required = false) String customerLevel,
            @RequestParam(required = false) String industry,
            @RequestParam(required = false) String customerSource,
            @RequestParam(required = false) Boolean isActive) {
        
        log.info("获取客户列表: page={}, size={}, companyName={}, customerLevel={}", 
                page, size, companyName, customerLevel);
        
        Map<String, Object> result = customerService.getCustomers(
                page, size, companyName, contactPerson, customerLevel, 
                industry, customerSource, isActive);
        
        return Result.success(result);
    }

    /**
     * 获取客户详情
     */
    @GetMapping("/{id}")
    public Result<Customer> getCustomer(@PathVariable Integer id) {
        log.info("获取客户详情: id={}", id);
        
        Customer customer = customerService.getCustomerById(id);
        if (customer == null) {
            return Result.error(404, "客户不存在");
        }
        
        return Result.success(customer);
    }

    /**
     * 创建客户
     */
    @PostMapping
    public Result<Customer> createCustomer(@Valid @RequestBody Customer customer) {
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        log.info("创建客户: companyName={}, creator={}", customer.getCompanyName(), username);
        
        // 检查公司名称是否已存在
        if (customerService.existsByCompanyName(customer.getCompanyName())) {
            return Result.error(400, "公司名称已存在");
        }
        
        Customer createdCustomer = customerService.createCustomer(customer, username);
        return Result.success(createdCustomer);
    }

    /**
     * 更新客户
     */
    @PutMapping("/{id}")
    public Result<Customer> updateCustomer(@PathVariable Integer id, @Valid @RequestBody Customer customer) {
        log.info("更新客户: id={}, companyName={}", id, customer.getCompanyName());
        
        customer.setId(id);
        
        // 检查公司名称是否已被其他记录使用
        if (customerService.existsByCompanyNameAndNotId(customer.getCompanyName(), id)) {
            return Result.error(400, "公司名称已存在");
        }
        
        Customer updatedCustomer = customerService.updateCustomer(customer);
        if (updatedCustomer == null) {
            return Result.error(404, "客户不存在");
        }
        
        return Result.success(updatedCustomer);
    }

    /**
     * 删除客户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteCustomer(@PathVariable Integer id) {
        log.info("删除客户: id={}", id);
        
        // 检查是否有关联的业务
        if (customerService.hasRelatedBusinesses(id)) {
            return Result.error(400, "该客户下还有关联的业务，无法删除");
        }
        
        // 检查是否有关联的工单
        if (customerService.hasRelatedWorkOrders(id)) {
            return Result.error(400, "该客户下还有关联的工单，无法删除");
        }
        
        boolean deleted = customerService.deleteCustomer(id);
        if (!deleted) {
            return Result.error(404, "客户不存在");
        }
        
        return Result.success();
    }

    /**
     * 批量删除客户
     */
    @PostMapping("/batch-delete")
    public Result<Map<String, Object>> batchDeleteCustomers(@RequestBody Map<String, List<Integer>> request) {
        List<Integer> ids = request.get("ids");
        log.info("批量删除客户: ids={}", ids);
        
        if (ids == null || ids.isEmpty()) {
            return Result.error(400, "请选择要删除的客户");
        }
        
        Map<String, Object> result = customerService.batchDeleteCustomers(ids);
        return Result.success(result);
    }


    /**
     * 获取客户统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getCustomerStats() {
        log.info("获取客户统计信息");
        
        Map<String, Object> stats = customerService.getCustomerStats();
        return Result.success(stats);
    }
}